package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.mapper.NoticeMapper;
import cn.tedu._03vehicle.pojo.vo.NoticeListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Tag(name = "03-公告管理模块")
@RequestMapping("/v1/notice")
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 1.首页公告展示
     */
    @GetMapping("/list")
    @Operation(summary = "查询首页公告")
    @ApiOperationSupport(order = 10)
    public JsonResult listNotice(){
        /*
            * 确定缓存的数据: List<NoticeListVO> ---> [{},{},{},{},{},{},{},{},{},{}]
            * 数据类型选择: 字符串String
            * key设计: vehicle_index

            1.从Redis中查询数据;
            2.如果Redis中存在数据，则直接返回结束;
            3.如果Redis中不存在数据:
              3.1 从MySQL数据库中查询数据;
              3.2 并缓存到Redis中,设置过期时间为30秒;
         */
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable redisData = ops.get("vehicle_index");
        if (redisData != null){//Redis中存在首页数据
            log.debug("首页数据来自于Redis数据库");
            return JsonResult.ok(redisData);
        }
        //Redis中不存在首页数据
        List<NoticeListVO> noticeListVOS = noticeMapper.listNotice();
        //将首页数据缓存到Redis中
        ops.set("vehicle_index", (Serializable) noticeListVOS, 30, TimeUnit.SECONDS);
        log.debug("首页数据来自于MySQL数据库");

        return JsonResult.ok(noticeListVOS);
    }
}










